package com.bsy.videostation.manager

import android.os.Parcelable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.bsy.common.constant.CATEGORY_INFO
import com.bsy.common.constant.HAS_LOGIN
import com.bsy.common.constant.USER_INFO_DATA
import com.bsy.framework.manager.KvManager
import com.bsy.network.constant.KEY_TOKEN
import com.bsy.videostation.constant.kvSaveHistoryKey
import com.bsy.videostation.model.VideoEntity
import com.bsy.videostation.model.res.UserInfo
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * Created by Lucy on 2023/10/19.
 * Copyright
 * 描述 :
 */
class UserManager {
    private val userLiveData = MutableLiveData<UserInfo?>()
    private var userInfo: UserInfo? = null

    init {
        userInfo = KvManager.getParcelable(USER_INFO_DATA, UserInfo::class.java)
    }

    /**
     * 是否登录
     * @return Boolean
     */
    fun isLogin(): Boolean {
        return KvManager.getBoolean(HAS_LOGIN, false)
    }

    /**
     * 添加一条历史记录
     *
     * @param data
     */
    fun addHistory(data: VideoEntity) {
        val historyList = getHistoryList()
        // 判断 data.id 是否存在于 historyList 中
        val exists = historyList.any { it.id == data.id }
        if (!exists) {
            historyList.add(data)
        } else
            replaceInSet(historyList, data)
        KvManager.saveList(kvSaveHistoryKey, historyList)
    }

    // 替换集合中的对象
    private fun replaceInSet(set: LinkedHashSet<VideoEntity>, newElement: VideoEntity) {
        // 找到具有相同 id 的对象
        val existingElement = set.find { it.id == newElement.id }

        // 如果存在则移除旧对象
        if (existingElement != null) {
            set.remove(existingElement)
        }

        // 添加新对象
        set.add(newElement)
    }

    /**
     * 获取历史记录
     *
     * @return
     */
    fun getHistoryList(): LinkedHashSet<VideoEntity> {
        val data = KvManager.getString(kvSaveHistoryKey, "")
        if (data.isEmpty()) return linkedSetOf()
        val result = Gson().fromJson<LinkedHashSet<VideoEntity>>(data, object : TypeToken<LinkedHashSet<VideoEntity>>() {}.type) ?: linkedSetOf()
        return result
    }

    /**
     * 保存用户信息
     * @param user
     */
    fun saveUserInfo(user: UserInfo?) {
        KvManager.saveParcelable(USER_INFO_DATA, user)
        userInfo = user
        if (userLiveData.hasObservers()) {
            userLiveData.postValue(user)
        }
    }


    /**
     * 获取用户信息
     * @return User
     */
    fun getUserInfo(): UserInfo? {
        return userInfo
    }

    /**
     * 获取token
     * @return token
     */
    fun getToken(): String {
        return KvManager.getString(KEY_TOKEN, "")
    }

    /**
     * 保存token
     */
    fun saveToken(token: String) {
        KvManager.save(KEY_TOKEN, token)
    }

    /**
     * 首页分类信息
     */
    fun saveCategory(category: Parcelable) {
        KvManager.saveParcelable(CATEGORY_INFO, category)
    }

    fun <T : Parcelable> getCategory(tClass: Class<T>?): T? {
        return KvManager.getParcelable(CATEGORY_INFO, tClass)
    }

    /**
     * 清除用户信息
     */
    fun clearUserInfo() {
        if (userLiveData.hasObservers()) {
            userLiveData.postValue(null)
        }
        clearAllKeys()
    }

    private fun clearAllKeys() {
        KvManager.removeKey(USER_INFO_DATA)
        KvManager.removeKey(HAS_LOGIN)
        KvManager.removeKey(KEY_TOKEN)
    }

    /**
     * 获取用户LiveData
     * @return LiveData<User>
     */
    fun getUserLiveData(): LiveData<UserInfo?> {
        return userLiveData
    }

    /**
     * 保存登录状态
     */
    fun saveLogin(isLogin: Boolean) {
        KvManager.save(HAS_LOGIN, isLogin)
    }
}